﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;

namespace DBUtility
{
    public static class DBHelper
    {
        /// <summary>
        /// 返回值为连接字符串
        /// </summary>
        /// <returns></returns>
        public static string getConnection()
        {
            string connstr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
            return connstr;
        }
        static SqlConnection con = new SqlConnection(getConnection());
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public static object GetScaler(string sql)
        {
            SqlCommand cmd = new SqlCommand(sql, con);
            try
            {
                con.Open();
                return cmd.ExecuteScalar();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                con.Close();
            }
        }
        /// <summary>
        /// 查询语句
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public static DataTable GetTable(string sql)
        {
            SqlDataAdapter sda = new SqlDataAdapter(sql, con);
            DataSet ds = new DataSet();
            try
            {
                sda.Fill(ds, "aa");
                return ds.Tables["aa"];
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// insert,update,delete,返回受影响行数。
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public static int ExecuteQuery(string sql)
        {
            SqlCommand cmd = new SqlCommand(sql, con);
            try
            {
                con.Open();
                return cmd.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                con.Close();
            }
        }
    }
}
